package com.chinaoct.siku.application;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class BimApplication {

    @Value("${bim.identity.client_id}")
    private String client_id;
    @Value("${bim.identity.client_secret}")
    private String client_secret;
    @Value("${bim.identity.getToken}")
    private String getTokenUrl;
    @Value("${bim.identity.getUserInfo}")
    private String getUserInfoUrl;


    public Map<String, String> loginByBimOauth(String code) {
        String tokenUrl= this.getTokenUrl +"?client_id="+client_id+"&client_secret="+client_secret+"&code="+code;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(tokenUrl);
        HttpPost post1 = null;
        String result;
        try {
            HttpResponse response = httpClient.execute(post);
            result = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSONObject.parseObject(result);
            if(jsonObject.getBoolean("success")){
                JSONObject json= jsonObject.getJSONObject("result");
                String token = json.getString("access_token");
                String userInfoUrl=this.getUserInfoUrl+"?client_id="+client_id+"&access_token="+token+"&attributeNames=username";
                post1=new HttpPost(userInfoUrl);
                HttpResponse response1 = httpClient.execute(post1);
                String result1 = EntityUtils.toString(response1.getEntity());
                JSONObject jsonObject1 = JSONObject.parseObject(result1);
                if(jsonObject1.getBoolean("success")){
                    JSONObject json1= jsonObject1.getJSONObject("result");
                    JSONObject user = json1.getJSONObject("user");
                    String username = user.getString("username");
                    JSONArray systems = json1.getJSONArray("systems");
                    String name = systems.getJSONObject(0).getJSONArray("accounts").getJSONObject(0).getString("fullname");
                    //String name = user.getString("fullname");
                    Map<String,String> map = new HashMap<>();
                    map.put("username",username);
                    map.put("name",name);
                    return  map;
                }else {
                    log.error(jsonObject1.getJSONObject("result").getString("errMessage"));
                    throw new RuntimeException("当前账号无权限，请联系管理员");
                }
            }else{
                log.error(jsonObject.getJSONObject("result").getString("errMessage"));
                throw new RuntimeException("当前账号无权限，请联系管理员");
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new RuntimeException(e.getMessage());
        }finally{
            if (null != post) {
                post.releaseConnection();
            }
            if (null != post1) {
                post1.releaseConnection();
            }
            httpClient = null;
        }
    }
}
